package edu.uiuc.ncsa;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.UUID;

/**
 * @author : Sachith Dhanushka (sachith.dhanushka@gmail.com)
 * @date : Jun 14, 2008 - 10:47:31 PM
 */
public class ResponseHandler {

    public static void sendTextFileToBrowser(File file, HttpServletResponse response) {

        try {
            System.out.println("Writing to file");
            if (file != null) {
                response.setContentType("text/xml");
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + file.getName() + '"');
                BufferedReader reader = new BufferedReader(new FileReader(file));

                String str;
                PrintWriter writer = response.getWriter();
                while ((str = reader.readLine()) != null) {
                    //                    System.out.println("writer = " + str);
                    writer.write(str);
                }

                reader.close();
                writer.close();
            } else {
                sendError(response, "Could not generate KML File");
            }
        } catch (IOException e) {
            sendError(response, e.getMessage());
        }
    }

    public static void sendZipFileToBrowser(File file, HttpServletResponse response) {
        try {
            System.out.println("Writing to file");
            if (file != null) {
                response.setContentType("application/x-zip-compressed");
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"" + file.getName() + '"');
                FileInputStream inStream = new FileInputStream(file);


                int sizeRead = 256;
                byte[] buf = new byte[1024];

                ServletOutputStream out = response.getOutputStream();

                while ((sizeRead = inStream.read(buf)) != -1) {
                    out.write(sizeRead);
                }

//                String str;
//                PrintWriter writer = response.getWriter();
//                while ((str = reader.readLine()) != null) {
//                    //                    System.out.println("writer = " + str);
//                    writer.write(str);
//                }
//
//                reader.close();
                //out.flush();
                inStream.close();
            } else {
                sendError(response, "Could not generate KML File");
            }
        } catch (IOException e) {
            sendError(response, e.getMessage());
        }
    }

    public static void sendFileToGEarth(File file, HttpServletResponse response) {

        try {
            System.out.println("Writing to file");
            if (file != null) {
                response.setContentType("application/octet-stream");
                response.setHeader("Content-Disposition",
                        "inline; filename=\"" + file.getName() + '"');
                InputStream istream = new FileInputStream(file);

                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                int start = 0;
                int length = 1024;
                byte[] buff = new byte[length];

                while (istream.read(buff, start, length) != -1) {
                    byteArrayOutputStream.write(buff, start, length);
                }

                response.setContentLength(byteArrayOutputStream.size());
                response.getOutputStream().write(byteArrayOutputStream.toByteArray());
                //response.getOutputStream().flush();

                istream.close();
            } else {
                sendError(response, "Can not generate KML File");
            }
        } catch (IOException e) {
            sendError(response, e.getMessage());
        }
    }

    public static void sendFileToBrowser(String fileContent, HttpServletResponse response) {

        try {

            if (fileContent != null) {
                response.setContentType("text/xml");
                response.setHeader("Content-Disposition",
                        "attachment; filename=\"output.kml\"");


                int i;
                PrintWriter writer = response.getWriter();
                writer.write(fileContent);

                writer.close();
            } else {
                sendError(response, "Can not generate KML File");
            }
        } catch (IOException e) {
            sendError(response, e.getMessage());
        }
    }

    public static void sendError(HttpServletResponse response, String message) {
        try {
            PrintWriter writer = response.getWriter();

            writer.write("<html><body>");
            writer.write("<h4>" + message + "</h4>");
            writer.write("</body></html>");
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void showInGEarth(File kmlFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        // keep a handle to the file in the context and send a key back to the browser
        // when google maps API requests the file, using the key we sent, retrieve the
        // file from that id, from the session and write it back.
        String filePath = kmlFile.getAbsolutePath();
        String hashKey = UUID.randomUUID().toString();

        System.out.println("hashKey = " + hashKey);

        String tomcatHome = System.getProperty("catalina.home");
        File fileDownloadFolder = new File(tomcatHome, "webapps/ROOT/kml/");
        if (!fileDownloadFolder.isDirectory()) {
            fileDownloadFolder.mkdir();
        }
        File downloadableFile = new File(fileDownloadFolder, hashKey + ".kml");
        copy(kmlFile, downloadableFile);

        // set the id and the filepath to the session
        ServletContext context = request.getSession().getServletContext();
        context.setAttribute(hashKey, filePath);
        HttpSession session = request.getSession();
        session.setAttribute("FileIdString", hashKey + ".kml");
        session.setAttribute("GoogleMapKey", "ABQIAAAAOOkX2b_UCJ-Acoc3JYgQhBTUboJREloKu3nsfpthwLPJIwhO3RR2mOL2vNTf_YOBvOgsf6MS9ME2PA");

        // this is for localhost
//        session.setAttribute("GoogleMapKey", "ABQIAAAAcnHznFYiAVCZNRGaBDqskxTwM0brOpm-All5BF6PoaKBxRWWERRPOrSGTT5ENyzZ_sfOPuoV__3fdA");

        response.sendRedirect("gearth.jsp");
//        response.sendRedirect("kmlFileHandler.jsp?fileId=" + hashKey);
    }

    private static String loadFile(File gearthHTML) {
        String fileContent = "";
        try {
            BufferedReader in = new BufferedReader(new FileReader(gearthHTML));

            String str;
            while ((str = in.readLine()) != null) {
                fileContent += str;
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileContent;
    }

    // Copies src file to dst file.
    // If the dst file does not exist, it is created
    private static void copy(File src, File dst) throws IOException {
        InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        in.close();
        out.close();
    }


}
